<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click.native="openImport">导入excel</el-button>
          <el-button type="danger" size="small" @click="exportData">导出excel</el-button>
          <el-button type="primary" size="small" @click.native="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <div @click="showQrCode(scope.row.staffPhoto)">
                <image-holder :src="scope.row.staffPhoto" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[10, 15, 20, 30]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <addor-edit ref="AddEmployee" @close="showDialog=false" @closeUpdate="closeUpdate" />
      </el-dialog>
    </div>
    <el-dialog
      :visible.sync="showDialogRole"
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <assign-role ref="assignRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
    </el-dialog>
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import QrCode from 'qrcode'
import { delEmployee, getEmployeeList } from '@/api/employees'
// import PageTools from '@/components/PageTools'
import EmployeeEnum from '@/constant/employees'
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
import addorEdit from './empDialog.vue'
import assignRole from './assignRole.vue'
export default {
  components: {
    addorEdit,
    assignRole
  },
  data() {
    return {
      list: [],
      curEmployeId: '',
      page: 1, // 当前页码
      size: 10, // 每页几条
      total: 0, // 总共数据条数
      showDialog: false,
      showDialogRole: false, // 分配角色框
      showCodeDialog: false
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res, '员工列表')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
        this.$message.error('获取员工数据失败')
      }
    },
    formatEmployment(data) {
      // console.log('执行一次formatEmployment')
      // // 对后端返回的类型的编码进行翻译 ，还原成 中文
      // const rs = EmployeeEnum.hireType.find(item => item.id === id)
      // return rs.value
      return hireType[data] || '未知'
    },
    // 会自动接收当前点击的页码
    handleCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 每页几条
    handleSizeChange(curSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.size = curSize
      // 2. 重发请求
      this.loadEmployeeList()
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该员工数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重发请求
        this.loadEmployeeList()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },
    // 添加员工后关闭重新渲染渲染数据
    closeUpdate() {
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeeList()
    },
    // 重置表单
    hClose() {
      this.$refs.AddEmployee.resetForm()
    },
    // 进入导入页面
    openImport() {
      this.$router.push('import')
    },
    // 导出员工数据
    exportData() {
      import('@/vendor/Export2Excel').then(async excel => {
        const newsize = this.total
        console.log(newsize, '总条数')
        const res = await getEmployeeList(this.page, newsize)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hAssignRole(id) {
      this.showDialogRole = true
      // console.log(id)
      this.curEmployeId = id
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
        // console.log('子组件中的props', this.$refs.assignRole.employeeId)
      })
    },
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 请求回来的数据转换为可读数据，封装函数
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    }
  }
}
</script>
